import 'dart:convert';

import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:huxiaodui/background_run/bg_channel.dart';
import 'package:huxiaodui/api/model/mobile_app_model.dart';
import 'package:huxiaodui/utils/position.dart';
import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/store/store.dart';
import 'package:huxiaodui/main.dart';
import 'package:huxiaodui/view/index/map_page/map_controller.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:flutter/widgets.dart';
import 'package:permission_handler/permission_handler.dart';

class GlobalController extends ChangeNotifier {
  /// 单例模式
  static final GlobalController _instance = GlobalController._internal();
  factory GlobalController() {
    return _instance;
  }
  GlobalController._internal();

  init() async {
    await Store.reload();
    Map<String, dynamic>? location = await Store.position.get();
    if (location != null) {
      MapController().currLatLng = LatLng(
          double.parse(location["latitude"].toString()),
          double.parse(location["longitude"].toString()));
      MapController().moveMap(latLng: MapController().currLatLng!);
      MapController().refresh();
    }

    /// 获取权限后才能启动
    await Permission.location.request();
    await Permission.locationAlways.request();

    getPosition();
    FlutterBackgroundService()
        .on("Position")
        .listen((Map<String, dynamic>? res) async {
      if (res == null) return;
      Store.position.save(res);
      MapController().currLatLng = LatLng(
          double.parse(res["latitude"].toString()),
          double.parse(res["longitude"].toString()));
      MapController().updateMarkers();
    });
  }

  ///用户信息
  MobileAppModel? user;

  login(MobileAppModel mobileApp) async {
    GlobalController().user = mobileApp;
    await Store.mobileApp.save(mobileApp);
    FlutterBackgroundService().invoke(BgChannelType.mqttReconnect);
    notifyListeners();
  }

  logout() async {
    Store.auth.del();
    GlobalController.toFirst();
    GlobalController().user = null;
    MapController().showMarkerInfo = null;
    MapController().alarms = [];
    MapController().mobileApps = [];
    MapController().refresh();
    await Store.mobileApp.del();
    MapController().updateMarkers();
    FlutterBackgroundService().invoke(BgChannelType.mqttReconnect);
    notifyListeners();
  }

  ///返回首页
  static toFirst({bool? showDrawer}) {
    navigatorKey.currentState?.popUntil((route) => route.isFirst);
    if (showDrawer != null) {
      if (showDrawer) {
        scaffoldKey.currentState?.openDrawer();
      } else {
        scaffoldKey.currentState?.closeDrawer();
      }
    }
  }

  ///刷新页面数据
  void refresh() {
    notifyListeners();
  }

  ///展示时间距离
  static String durationToString(Duration duration) {
    var timeDistance = "";
    if (duration.inDays > 0) {
      timeDistance = "${duration.inDays} 天前";
    } else if (duration.inHours > 0) {
      timeDistance = "${duration.inHours} 小时前";
    } else if (duration.inMinutes > 0) {
      timeDistance = "${duration.inMinutes} 分钟前";
    } else {
      timeDistance = "刚刚";
    }
    return timeDistance;
  }

  getPosition() async {
    Position().destroy();
    await Position().init(
      locationInterval: 60 * 1000,
      onEvent: (Map<String, Object> res) async {
        Store.position.save(res);
        MapController().currLatLng = LatLng(
            double.parse(res["latitude"].toString()),
            double.parse(res["longitude"].toString()));
        MapController().updateMarkers();
        Api.push.send(
            "position",
            jsonEncode(
                {"latitude": res["latitude"], "longitude": res["longitude"]}));

      },
    );
    // await Future.delayed(const Duration(seconds: 5)).then((value) {
    //   // Position().destroy();
    // });
  }
}
